package com.time.hellotime.webserver.request;

import com.google.gson.Gson;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.RestRequest;
import com.yanzhenjie.nohttp.rest.StringRequest;

/**
 * 封装一个解析所有通用的javaBean的请求类，返回的数据对应的就是的一个javaBean
 * 例如： User, UserInfo, Order等...
 * Created by Bing on 2016/8/23.
 * E-mail is tx16bing@163.com
 */
public class BaseRequest<T> extends RestRequest<T> {
    private Class<T> clazz;

    public BaseRequest(String url, Class<T> clazz) {
        //默认设置请求方式是GET
        this(url, RequestMethod.POST, clazz);
    }

    public BaseRequest(String url, RequestMethod requestMethod, Class<T> clazz) {
        super(url, requestMethod);
        this.clazz = clazz;
    }

    @Override
    public T parseResponse(Headers responseHeaders, byte[] responseBody) throws Exception {
        String result = StringRequest.parseResponseString(responseHeaders, responseBody);
        try {
            return new Gson().fromJson(result, clazz);
        } catch (Exception e) {
            try {
                // 传进来的JavaBean一定要提供无参构造器
                clazz.newInstance();
            } catch (Exception e1) {
            }
        }
        return null;
    }

}
